﻿using Dapr.Client;
using Hangfire.Logging;
using Microsoft.AspNetCore.Hosting;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;

namespace BlazorApp4.Data
{
    public class HelloJobService: BackgroundService
    {
        private readonly ILog _log;
        private IHostingEnvironment Environment;
        private readonly DaprClient daprClient = new DaprClientBuilder().Build();
        const string DAPR_STATE_STORE = "statestore";
        const string DAPR_ALL_FILE = "all_files";

        public HelloJobService(IHostingEnvironment _environment)
        {
            //构造函数注入
            _log = LogProvider.GetLogger(typeof(HelloJobService));
            this.Environment = _environment;

        }

        //每3天遍历一次，每次只删除一个文件
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var filePath = Path.Combine(this.Environment.WebRootPath,"files/");
            List<FileDetail> loadedFiles = new List<FileDetail>();

            while (!stoppingToken.IsCancellationRequested)
            {
                loadedFiles = await daprClient.GetStateAsync<List<FileDetail>>(DAPR_STATE_STORE, DAPR_ALL_FILE);

                if (loadedFiles.Count != 0)
                {
                    var file = loadedFiles.Last();
                    var diff = DateTime.Now - Convert.ToDateTime(file.UploadTime);

                    if (diff.Days > 100)
                    {
                        if (File.Exists(filePath + file.Name))
                        {
                            File.Delete(filePath + file.Name);
                            _log.Warn("删除" + file.Name +"成功");
                        }
                        loadedFiles.Remove(file);
                        await daprClient.SaveStateAsync(DAPR_STATE_STORE, DAPR_ALL_FILE, loadedFiles);
                        _log.Info("删除" + filePath + file.Name + "成功");
                    }
                }
                await Task.Delay(TimeSpan.FromDays(3), stoppingToken);
            }
        }
    }
}
